package file;
//TODO closing the saveAs window is impossible

import gui2.MainWindow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import schedule.AppointmentList;

public class AppointmentFileConnectionImpl implements IFileConnection{
	private AppointmentList appointments;
	private MainWindow frame;
	
	public AppointmentFileConnectionImpl(AppointmentList list, MainWindow frame) {
		appointments = list;
		this.frame = frame;
	}
	
	@Override
	public boolean changes() {
		return appointments.size()>0;
	}

	@Override
	public void save(File f) throws IOException {
		try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f))){
			output.writeObject(appointments);
		} catch(IOException e){
			e.printStackTrace();
			throw new IOException("an error occured while saving the file");
		}
	}

	@Override
	public void newFile() throws IOException {
		appointments.clear();
		frame.getAppointmentPanel().refresh();
	}

	@Override
	public void open(File f) throws IOException {
		try(ObjectInputStream input = new ObjectInputStream(new FileInputStream(f))){
			appointments.clear();
			appointments.addAll((AppointmentList) input.readObject());
			frame.getAppointmentPanel().refresh();
		} catch(IOException | ClassNotFoundException e){
			e.printStackTrace();
			throw new IOException("error while opening the file: "+ f, e);
		}
	}

}
